package tools;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.JOptionPane;


public class TabQuery {

	private int timeBetweenPagePulls = 1000;
	
	
	/*
	public static void main(String[] args) {
		String query = "http://url.com/find.php?value=";
		String query2 = "&stype=name";
		String search = "";
		
		if( args.length == 1 )	{
			search = args[0].replace(" ", "+");
			query = query + search + query2;
		}
		else	{	// print usage
			System.out.println("Incorrect usage detected.");
			System.out.println("Usage: java tools.TabQuery \"Song Title\"");
			return;
		}
		
		TabQuery tq = new TabQuery();
		ArrayList<Tab> allTabs = tq.processQuery(WebGet.getPage(query));
		
		for(int x=0; x < allTabs.size(); x++)
			System.out.println("["+x+"]: " + allTabs.get(x));
		         
		try {
			String curLine = ""; // Line read from standard in        
			InputStreamReader converter = new InputStreamReader(System.in);
			BufferedReader in = new BufferedReader(converter);
			System.out.println("Please enter a tab number from above to view it (type 'quit' to exit): ");
			
			boolean done = false;
			
			while( !done )	{
				curLine = in.readLine();

				if( !curLine.startsWith("quit") )	{
					int a = Integer.parseInt(curLine);
					if( a >= 0 && a < allTabs.size() )	{
						allTabs.get(a).displayTab();
					}	
					else	{
						System.out.println("ERROR: " + a + "is an invalid selection. Please try again.");
					}
					
					curLine = "";
					System.out.println("Please enter a tab number from above to view it (type 'quit' to exit): ");
				}
				else	{
					System.out.println("Exiting TabQuery...");
					return;
				}
			}

			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		         
	}
	*/
	
	public TabQuery()	{
		
	}	

	public String[] readQueryStructureFromFile()	{
		try	{
			FileInputStream fstream = new FileInputStream("../qfile.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));

			String[] query = new String[2]; 
			query[0] = br.readLine();
			query[1] = br.readLine();
			
			in.close();
			
			return query;
		} catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return null;
	}
	
	
	public ArrayList<Tab> findTabs(String searchString)	{		
		String[] query;

		if( (query=readQueryStructureFromFile()) == null )	{
			JOptionPane.showMessageDialog(null, "Error loading the query structure file!\nSearch halted.");
			return null;
		}
	
		searchString = searchString.trim();
		searchString = searchString.replace(" ", "+");
		
		ArrayList<Tab> results = new ArrayList<Tab>();
		String page = WebGet.getPage(query[0]+searchString+query[1]);

		ArrayList<Tab> p = processQuery(page);
		
		if( p == null )
			return null;
		
		results.addAll(p);
		
		String[] pages = getMultiplePages(page);
		String front = query[0].substring(0, query[0].lastIndexOf("/")+1);
		
		// only one page and we already processed it
		if( pages == null )
			return results;
		
		for(int x=0; x < pages.length; x++)	{
			results.addAll(processQuery(WebGet.getPage(front+pages[x])));

			try {
				Thread.sleep(timeBetweenPagePulls);	// wait 3 seconds between page loads
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		return results;
	}

	public String[] getMultiplePages(String page)	{
		String[] allPages = new String[25];
		String[] split = page.split("<div class=\"paging\" align=\"center\">");
		
		// if there is only 1 page of results
		if( split.length != 2 )
			return null;
		
		String pageLinks = split[1];
		pageLinks = pageLinks.split("</div>")[0];

		String searchPages[] = pageLinks.split("<a href=\"");
		
		// one bogus page at the end, one non-listing in the front
		allPages = new String[searchPages.length - 2];
		
		for(int x=1; x < searchPages.length-1; x++)	{
			allPages[x-1] = searchPages[x].substring(0, searchPages[x].indexOf("\""));
			System.out.println("Page #" + (x+1) + ": " + allPages[x-1]);
		}
				
		return allPages;
	}
	
	public ArrayList<Tab> processQuery(String input)	{
		int index = input.indexOf("<table cellspacing=\"1\" class=\"tresults\"");
		int lastIndex = input.indexOf("</table>", index);


		if( index == -1 )	// string above not found
			return null;	// no matching results

//		System.out.println("input: " + input);		
		
		String a = input.substring(index, lastIndex);
		
		String[] rows = a.split("</tr>");	// cut it into rows
		String bandName = "";

		ArrayList<Tab> tabsFound = new ArrayList<Tab>();
		
		for(int x=0; x < rows.length; x++)	{
			
			String[] result = rows[x].split("</td>");	// cut it into cells
			
			if( result.length == 7 )	{ // omit power tab or guitar pro files
				continue;
			}
			else if( result.length == 5 )	{	// This tab is for us!
				// result[] 
				// result 0: band name
				// result 1: song name + song URL
				// result 2: rating + # of rated
				// result 3: tab type
				
				// Result 0: Band name parsing
				if( result[0].contains("&nbsp;") )	{
					// Use previously set band name
				}
				else	{	// band name changed, set the new one
					String partial = result[0].split("</a>")[0];
					bandName = partial.substring(partial.lastIndexOf("\">") + 2);
					bandName = WebGet.stripHTML(bandName);
				}

				// Result 1: Song name and URL parsing
				String[] partialSong = result[1].split("class=\"song\"");
				int firstQuote = partialSong[0].lastIndexOf("<a href=\"") + 9;
				int lastQuote = partialSong[0].lastIndexOf("\"");
				String songLink = partialSong[0].substring(firstQuote, lastQuote);
				
				int firstBracket = partialSong[1].indexOf(">")+1;
				int lastBracket = partialSong[1].indexOf("</a>");
				String songName = partialSong[1].substring(firstBracket, lastBracket);
				songName = WebGet.stripHTML(songName);

				// Result 2: Song rating and number of raters parsing
				String[] rating = result[2].split("class=\"ratdig\">");
				String rated;
				String numRated;
				if( rating[0].contains("<span class=\"rating\"><span class=\"") )	{
					rated = rating[0].split("<span class=\"rating\"><span class=\"")[1];
					rated = rated.substring(0, rated.indexOf("\""));
					numRated = rating[1].substring(0, rating[1].indexOf("<"));
				}
				else	{
					rated = "NO RATING";
					numRated = "0";
				}
			
				// Result 3: Tab type parsing
				String tabType = result[3].split("<strong>")[1];
				tabType = tabType.substring(0, tabType.indexOf("<"));
				tabType = tabType.toUpperCase();
				
				if( !tabType.contains("TAB PRO") && !tabType.contains("VIDEO LESSON") )
					tabsFound.add(new Tab(bandName, songName, songLink, rated, numRated, tabType));
				
			}
		}

		return tabsFound;
	}
	
	
}
